package surreal.triviamaster.gui;

import surreal.triviamaster.R;
import surreal.triviamaster.beans.Category;
import surreal.triviamaster.database.LocalCache;
import surreal.triviamaster.utilities.TriviaMasterApplication;
import surreal.triviamaster.utilities.TriviaMasterService;
import surreal.triviamaster.utilities.Utilities;
import android.app.ListActivity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Toast;

public class AddCategoriesToQuestion extends ListActivity{
	private LocalCache db;
	private Category[] cats;
	//data on the question that was passed to this activity
	private Bundle qBundle;
	//tell wither or not the category was selected.  These refer to the same index as the cats array with 0 being empty
	private boolean[] catsChoosen;

	@Override
	  public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    setContentView(R.layout.add_categories_to_question);
	    
	    //getting the question that was passed to this activity
	    Bundle bundle = getIntent().getExtras();
	    qBundle = bundle.getBundle("bundle");
	    
    	db = ((TriviaMasterApplication) getApplication()).getLocalCache();
    	
    	//getting cats and creating the string of cats
    	cats = db.getAllCategories();
    	String[] catList=new String[cats.length];
    	catsChoosen = new boolean[cats.length];
    	
    	//handles changing orientation
    	final Bundle data = (Bundle) getLastNonConfigurationInstance();
    	if(data!=null) {
    		qBundle=data.getBundle("qBundle");
    		catsChoosen=data.getBooleanArray("catsChoosen");
    	}
    	
    	//creating the string list the fills the list view activity
    	for(int i=0;i<cats.length;i++) {
    		catList[i]=cats[i].getCategory();
    	}
    	setListAdapter(new ArrayAdapter<String>(this, R.layout.generic_list_item, catList));

    	ListView lv = getListView();
    	lv.setTextFilterEnabled(true);

    	// When clicked, open that activity
    	lv.setOnItemClickListener(new OnItemClickListener() {
    		public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		    	if(catsChoosen[position]) {
		    		catsChoosen[position]=false;
		    		parent.getChildAt(position).setBackgroundColor(Color.BLACK);
		    	} else {
		    		catsChoosen[position]=true;
		    		parent.getChildAt(position).setBackgroundColor(Color.YELLOW);
		    	}
    		}

    	});   
    	
    	//Submit Question
	    Button submit = (Button) findViewById(R.id.submit);
	    submit.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
            	if(isACatChoosen(catsChoosen)) {
            		if(Utilities.isNetworkAvailable(AddCategoriesToQuestion.this)) {
    	            	Intent intent = new Intent(TriviaMasterApplication.ACTION_INSERT_QUESTION, null, AddCategoriesToQuestion.this, TriviaMasterService.class);
	    				intent.putExtra("question", qBundle.getString("question"));
	    		    	intent.putExtra("acceptableAnswers", qBundle.getString("aAs"));
	    		    	intent.putExtra("fList", qBundle.getString("fList"));
	    		    	intent.putExtra("hint", qBundle.getString("hint"));
	    		    	
	    		    	String catsToUpload ="";
	    		    	for(int i=0;i<cats.length;i++) {
	    		    		if(catsChoosen[i]) {
		    		    		if(catsToUpload.equals("")) {
		    		    			catsToUpload+=cats[i].getId();
		    		    		} else {
		    		    			catsToUpload+=";"+cats[i].getId();
		    		    		}
	    		    		}
	    		    	}
	    		    	
	    		    	intent.putExtra("categories", catsToUpload);
	    		    	intent.putExtra("userId", db.getUserId());
	    		    	Log.d("AddCategoriesToQuestion Upload Question", "cats value: " + catsToUpload);
	    				startService(intent);
	    				
	    				//Notify the user
	    				Toast.makeText(AddCategoriesToQuestion.this, "Question Uploaded", 5000).show();
	    				
	    				//Move user to next page
	    		    	intent = new Intent(AddCategoriesToQuestion.this, TriviaMasterActivity.class);
	    		    	intent.putExtra("fromApp", true);
	    	  	      	startActivity(intent);
                	} else {
                		Toast.makeText(AddCategoriesToQuestion.this, TriviaMasterApplication.NETWORK_ERROR, 5000);
                	}
    				
				} else {
					//Notify the user
    				Toast.makeText(AddCategoriesToQuestion.this, "You must choose at least one category", 10000).show();
    				
				}
            }
        });
	    
	 	//Cancel button
	    Button cancel = (Button) findViewById(R.id.cancel);
	    cancel.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
            	
    				//Move user to next page
    		    	Intent intent = new Intent(AddCategoriesToQuestion.this, AddHints.class);
    		    	intent.putExtra("bundle", qBundle);
    	  	      	startActivity(intent);
            }
        });
	}
	
	/**
	 * return True if one of the categories have actually been choosen
	 */
	private boolean isACatChoosen(boolean[] catsChoosen) {
		
		for(int i=0;i<catsChoosen.length;i++) {
			if(catsChoosen[i])
				return true;
		}
		
		return false;
	}
	
	@Override
	public Object onRetainNonConfigurationInstance() {
		Bundle bundle = new Bundle();
		bundle.putBooleanArray("catsChoosen", catsChoosen);
		bundle.putBundle("qBundle", qBundle);
	    return bundle;
	}
}
